<template>
  <div>
    <t-dialog
      width="auto"
      class="dialog"
      placement="center"
      :header="false"
      :footer="false"
      :closeBtn="false"
      :visible.sync="visible"
      :close-on-overlay-click="false"
    >
      <div class="dialog-body">
        <div class="left">
          <div class="drawer-head">
            <h3>{{header}}</h3>
          </div>

          <div class="product-info">
            <h3>{{ row.title }}</h3>
          </div>

          <t-form :data="formData" :rules="rules" ref="form" layout="inline" label-align="top" @submit="onSubmit">
            <t-form-item v-if="formData.is_sn === 1" style="width: 100%;margin-right: 0;">
              <div style="width: 100%;">
                <t-table
                  rowKey="id"
                  :data="formData.snDataList"
                  :columns="columns"
                  :stripe="stripe"
                  :bordered="bordered"
                  :hover="hover"
                  :size="size"
                  :max-height="maxHeight"
                  :table-layout="tableLayout ? 'auto' : 'fixed'"
                  :showHeader="showHeader"
                  cellEmptyContent="-"
                  resizable
                  :loading="loading"
                >
                  <template #title-slot-sn>
                    <div class="flex align-center">
                      <p>SN码</p>
                    </div>
                  </template>
                  <template #title-slot-price>
                    <p></p>
                  </template>
                  <template #unit_price="{ row, rowIndex }">
                    <t-form-item style="width: 100%" :name="'snDataList.' + rowIndex + '.unit_price'" :labelWidth='0' :rules='rules.unit_price' >
                      <t-input-number label="￥" v-model="row.unit_price" :min="0" style="width: 100%" theme="column" placeholder="0.00"></t-input-number>
                    </t-form-item>
                  </template>
                  <template #unit_id="{ row, rowIndex }">
                    <t-form-item style="width: 100%" :name="'snDataList.' + rowIndex + '.unit_id'" :labelWidth='0' :rules='rules.unit_id' >
                      <t-select v-model="row.unit_id" :options="unitOptions" style="width: 100%" placeholder="选择单位" />
                    </t-form-item>
                  </template>
                  <template #remark="{ row, rowIndex }">
                    <t-textarea v-model="row.remark" autosize placeholder="请输入备注" />
                  </template>
                  <!--<template #option="{ row, rowIndex }">-->
                  <!--  <t-popconfirm theme="danger" placement="top-right" confirm-btn="删除" @confirm="handleDelete(row)">-->
                  <!--    <template #content>-->
                  <!--      <div>-->
                  <!--        <h3 class="popconfirm-title">确认删除？</h3>-->
                  <!--        <p>删除后数据将不可恢复！是否确认删除？</p>-->
                  <!--      </div>-->
                  <!--    </template>-->
                  <!--    <t-button theme="danger" variant="outline">删除</t-button>-->
                  <!--  </t-popconfirm>-->
                  <!--</template>-->
                </t-table>
              </div>
            </t-form-item>

            <template v-if="!(!!formData.is_sn)">
              <t-form-item name="unit_price" style="width: 168px;margin-right: 18px;">
                <template #label>
                  <p class="form-label2">进货价</p>
                </template>
                <t-input label="￥" v-model="formData.unit_price" :disabled="!!formData.is_sn" placeholder="0.00"></t-input>
              </t-form-item>
              <t-form-item name="quantity" style="width: 168px;margin-right: 18px;">
                <template #label>
                  <p class="form-label2">数量</p>
                </template>
                <t-input-number v-model="formData.quantity" :disabled="!!formData.is_sn" :min="1" placeholder="请输入"></t-input-number>
              </t-form-item>
              <t-form-item name="unit_id" style="width: 160px;margin-right: 0;">
                <template #label>
                  <p class="form-label2">单位</p>
                </template>
                <t-select v-model="formData.unit_id" :disabled="!!formData.is_sn" :options="unitOptions" placeholder="选择产品单位" />
              </t-form-item>
              <t-form-item name="remark" style="width: 100%;margin-right: 0;">
                <template #label>
                  <p class="form-label2">备注</p>
                </template>
                <t-textarea v-model="formData.remark" :disabled="!!formData.is_sn" :maxlength="50" placeholder="请输入备注" />
              </t-form-item>
            </template>
          </t-form>
          <div class="footer-btn">
            <div>
              <t-button theme="danger" v-if="type === 'again'" variant="outline" class="danger-btn" @click="cancelWarehousing">取消出库</t-button>
            </div>
            <t-space size="8px">
              <t-button theme="primary" class="" @click="confirmWarehousing">确定</t-button>
              <t-button theme="default" class="" @click="close">取消</t-button>
            </t-space>
          </div>
        </div>

      </div>
    </t-dialog>
  </div>
</template>

<script>
import { IconFont } from "tdesign-icons-vue";
import {classifyListApi} from "@/api/classify";
import ConfigRight from "@/pages/warehouse/components/product-warehousing/config-right.vue";

export default {
  name: 'ConfigInfo',
  components: {ConfigRight, IconFont},
  data() {
    return {
      visible: false,
      header: '编辑信息',
      confirmBtn: {
        text: '保存',
        theme: 'primary',
        loading: false
      },
      row: {},
      showInventory: true,
      formData: {
        product_id: '', // 产品ID
        unit_id: '',  // 单位ID
        quantity: '', // 数量
        is_sn: 1, // 开启SN序列号（0关闭；1开启）
        sn: '', // SN数据
        unit_price: '', // 含税单价（进货价）
        remark: '', // 备注（50个字内）
        snDataList: [
          {
            product_id: '', // 产品ID
            unit_id: '',  // 单位ID
            quantity: '', // 数量
            is_sn: 1, // 开启SN序列号（0关闭；1开启）
            sn: '', // SN数据
            unit_price: '', // 含税单价（进货价）
            remark: '', // 备注（50个字内）
          }
        ],
      },
      rules: {
        unit_price: [{ required: true, message: '请输入进货价', trigger: 'blur' }],
        unit_id: [{ required: true, message: '请选择单位', trigger: 'change' }],
        quantity: [
          { required: true, message: '请输入数量', trigger: 'change' },
          { min: 1, message: '数量必须大于0', trigger: 'change' }
        ],
      },
      unitOptions: [],
      switchValue: true,
      type: 'first',

      lists: [],
      size: 'medium',        unit_id: [{ required: true, message: '请输入产品单位', trigger: 'change' }],

      tableLayout: false,
      stripe: false,
      bordered: false,
      hover: true,
      showHeader: true,
      columns: [
        //{colKey: 'index', title: '序号', align: 'center', width: 62,},
        {colKey: 'sn', title: 'title-slot-sn', width: 220 },
        {colKey: 'unit_price', title: '进货价', width: 160 },
        {colKey: 'unit_id', title: '单位', width: 160 },
        {colKey: 'remark', title: '备注', width: 220 },
        //{colKey: 'option', title: '操作', fixed: 'right', width: 80},
      ],
      maxHeight: 200,
      loading: false,

      batchVisible: false,
      batchFormData: {
        codes: ''
      },

      productId: '',
      batchRules: {
        codes: [{ required: true, message: '请输入SN码', trigger: 'blur' }],
      },
    }
  },
  methods: {
    changeIsSN() {
      this.rules.unit_price = this.formData.is_sn === 1 ? [{ required: false, message: '请输入进货价', trigger: 'blur' }] : [{ required: true, message: '请输入进货价', trigger: 'blur' }]
    },
    onVisibleChange(val, context = {}) {
      // trigger 表示触发来源，可以根据触发来源自由控制 visible
      if (context && context.trigger !== 'confirm') {
        this.batchVisible = val;
      }
    },
    confirmSN() {
      this.$refs.batchForm.submit();
    },
    onBatchSubmit({ validateResult, firstError }) {
      if (validateResult === true) {
        // 对codes进行处理,按照逗号或换行符进行分割
        const codes = this.batchFormData.codes.split(/,|\n/).filter(item=> item)
        const snDataList = codes.map((item, index)=> ({
          sn: item,
          title: this.row.title,
          product_id: this.productId, // 产品ID
          unit_id: this.row.unit_id,  // 单位ID
          unit_title: this.row.unit_title || '',  // 单位ID
          quantity: 1, // 数量
          is_sn: 1, // 开启SN序列号（0关闭；1开启）
          unit_price: '', // 含税单价（进货价）
          remark: '', // 备注（50个字内）
        }))
        this.formData.snDataList = [...this.formData.snDataList, ...snDataList]
        // 按照SN码为参照进行去重处理
        this.formData.snDataList = this.formData.snDataList.reduce((acc, cur) => {
          const hasDuplicate = acc.some(item => item.sn === cur.sn);
          if (!hasDuplicate) {
            acc.push(cur);
          }
          return acc;
        }, []);

        this.batchVisible = false
        this.batchFormData.codes = ''
      } else {
        this.$message.error(firstError);
      }
    },
    handleDelete(row) {
      this.formData.snDataList = this.formData.snDataList.filter(item=> item.sn !== row.sn)
    },
    // 取消出库
    cancelWarehousing() {
      this.$emit('cancel', this.formData)
      this.close();
    },
    // 确认出库
    confirmWarehousing() {
      this.$refs.form.submit()
    },
    onSubmit({ validateResult, firstError }) {
      if (validateResult === true) {
        //if (this.formData.is_sn) {
        //  if (this.formData.snDataList.length === 0 && this.formData.quantity) {
        //    this.$message.error('请录入SN码')
        //    return
        //  }
        //} else {
        //  this.formData.snDataList = []
        //}

        console.log('formData', this.formData)

        this.$emit('confirm', this.formData)
        this.close();
      } else {
        this.$message.error(firstError);
      }
    },
    // 获取列表
    getList() {
      const params = {
        page: 1,  // 当前页
        limit: 9999,  // 每页条数
        belong_module: 'product_unit',
      }
      classifyListApi(params).then(res=> {
        this.unitOptions = res.data.map(item=> ({ label: item.title, value: item.id }))
      }).catch(err=> {
        console.log('err', err)
      })
    },
    open(row) {

      console.log('row', row)
      this.row = row
      this.visible = true
      this.productId = row.product_id
      this.formData = {
        title: row.title,
        product_id: this.productId, // 产品ID
        unit_id: row.unit_id,  // 单位ID
        unit_title: row.unit_title,  // 单位ID
        quantity: row.quantity, // 数量两位小数
        is_sn: row.is_sn,
        sn: row.sn,
        unit_price: row.unit_price,
        remark: row.remark || '',
        snDataList: [row]
      }
      this.getList()
    },
    close() {
      this.visible = false
    }
  }
}
</script>

<style lang="less" scoped>

/deep/ .t-form__controls {
  min-height: 0;
}

/deep/ .t-form__controls-content {
  min-height: 0;
}

/deep/ .dialog {

  .t-dialog--default {
    padding: 0;

    .t-dialog__body {
      padding: 0;
    }
  }
}

.dialog-body {
  display: flex;
}

.form-label2 {
  font-size: 16px;
  font-weight: 600;
  line-height: 22.4px;
  color: #000000E5;
}

.label-hint {
  font-size: 12px;
  font-weight: 400;
  line-height: 16.8px;
  padding-left: 8px;
  padding-right: 8px;
  color: var(--td-font-gray-2);
}

/deep/ .t-dialog__body {
  margin: 0 !important;
}

/deep/ .dialog-body {

  .t-input.t-size-l {
    min-height: 40px !important;
  }

  .t-input-number.t-size-l .t-input {
    font-size: 17px;
    min-height: 40px;
  }

  .t-input {
    //background-color: #FFFFFF !important;
  }

}


/deep/ .left {
  position: relative;
  width: 890px;
  padding: 32px 24px;
  padding-bottom: 24px;
  box-sizing: border-box;


  .drawer-head {
    color: black;
  }

  .product-info {
    padding: 12px;
    margin-top: 12px;
    margin-bottom: 24px;
    background-color: #F9F9F9;
    border-radius: var(--td-radius-medium);

    h3 {
      font-size: 16px;
      font-weight: 600;
      line-height: 22.4px;
      text-align: left;
      color: #000000;
    }

    p {
      font-size: 16px;
      font-weight: 400;
      line-height: 24px;
      text-align: left;
      color: #000000E5;
    }
  }
}


.footer-btn {
  width: 100%;
  display: flex;
  padding-top: 24px;
  align-items: center;
  justify-content: space-between;
}

.danger-btn {
  width: 112px;
  height: 40px;
  border-radius: var(--td-radius-medium);
}

.confirm-btn {
  width: 82px;
  height: 42px;
  color: #FFFFFF;
  font-size: 16px;
  font-weight: 400;
  line-height: 22.4px;
  border-radius: var(--td-radius-medium);
}

.cancel-btn {
  width: 82px;
  height: 42px;
  color: #FFFFFF;
  font-size: 16px;
  font-weight: 400;
  line-height: 22.4px;
  background-color: #B8B8B8;
  border-radius: var(--td-radius-medium);
}

.cancel-btn2 {
  width: 82px;
  height: 42px;
  font-size: 16px;
  font-weight: 400;
  line-height: 22.4px;
  border-radius: var(--td-radius-medium);
}
</style>
